package xyz.xpman.prisonerfitness.util;

import android.content.Context;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

public class StreamUtils {

    public static String get(@NotNull Context context, int id) {
        String read = "";

        try (InputStream stream = context.getResources().openRawResource(id)) {
            if (null != stream) {
                read = read(stream);
            }
        } catch (IOException ignore) { }

        return read;
    }

    public static String read(@NotNull InputStream stream) {
        return read(stream, "utf-8");
    }

    public static String read(@NotNull InputStream is, String encode) {
        String json = null;

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, encode))) {
            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            json =  sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return json;
    }



    public static void write(@NotNull InputStream in, @NotNull OutputStream out) {
        write(in, out, 1024);
    }

    public static void write(@NotNull InputStream in, @NotNull OutputStream out, int bufferSize) {
        int len;
        byte[] buf = new byte[bufferSize];

        try {
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static boolean write(@NotNull FileOutputStream fos, String dataString) {
        return write(fos, "utf-8", dataString);
    }

    public static boolean write(@NotNull FileOutputStream fos,
                                @NotNull String encode,
                                String dataString) {
        boolean success = true;

        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, encode))) {

            writer.write(dataString);

        } catch (IOException e) {
            success = false;
            e.printStackTrace();
        }

        return success;
    }
}